﻿using System.Configuration;
using System.Reflection;
using System.Windows;
using Core;
using Core.Infrastructure;
using Core.Interfaces;
using Core.IocHelpers;
using Core.Settings;
using log4net;
using TallyJ.Properties;
using TallyJ.Windows;
using SplashScreen=TallyJ.Windows.SplashScreen;

namespace TallyJ
{
  /// <summary>
  /// Interaction logic for App.xaml
  /// </summary>
  public partial class App
  {
    protected override void OnStartup(StartupEventArgs e)
    {
      base.OnStartup(e);

      // show the splash
      //var about = new SplashScreen();
      //about.Show();

      RegesterIoC();

      var log = IoC.Container.Resolve<ILog>();
      log.Info("Started");

      AbortIfWrongFrameworkVersion(log);

      LinkAppSettingsIntoCore();

      // StartPreparingNHibernate();

      var w = new Launch();
      w.Show();

      //about.Close();
    }

    private void AbortIfWrongFrameworkVersion(ILog log)
    {
      var frameworkTester = IoC.Container.Resolve<IFramework>();

      string message;
      if (!frameworkTester.IsVersion4(out message))
      {
        log.Info("Invalid framework: " + message);

        MessageBox.Show(
              message,
              "Unable to Execute", MessageBoxButton.OK, MessageBoxImage.Exclamation);

        Current.Shutdown();
      }
    }

    private void LinkAppSettingsIntoCore()
    {
      var coreAppSettings = IoC.Container.Resolve<IAppSettings>();
      coreAppSettings.LinkToSource(Settings.Default);
    }

    private void RegesterIoC()
    {
      AutoRegister.DoAutoRegistrations(IoC.Container); // local
      AutoRegister.DoAutoRegistrations(IoC.Container, Assembly.GetAssembly(typeof (IoC))); // core
      AutoRegister.DoAutoRegistrations(IoC.Container, Assembly.GetAssembly(typeof (DataXml.Extensions))); // core

      IoC.RegisterExternals();
      IoC.Container.RegisterType(typeof (ApplicationSettingsBase), typeof (Settings));
    }
  }
}